package com.example.shirodemo.dao;

import com.example.shirodemo.common.SerializeUtils;
import com.example.shirodemo.entity.AdminSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;

/**
 * ShiroTest   com.example.shirodemo.dao
 *
 * @author：黄玉刚 -成都电安惠科有限公司
 * @date： 2019/12/1 17:30
 * @Description ：
 */

public class MysqlSessionDao extends EnterpriseCacheSessionDAO {

    private static Logger logger = LoggerFactory.getLogger(MysqlSessionDao.class);

    @Autowired
    private AdminSessionMapper adminSessionMapper;

    @Override
    public void update(Session session) {

        logger.info("更新seesion" + session.getId());
        try {
            adminSessionMapper.set(new AdminSession(session.getId().toString(), SerializeUtils.serialize(session)));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除session
     */
    @Override
    public void delete(Session session) {

        logger.info("删除seesion" + session.getId());
        if (session == null || session.getId() == null) {
            return;
        }
        adminSessionMapper.delete(session.getId().toString());
    }


    /**
     * 创建session
     */
    @Override
    protected Serializable doCreate(Session session) {

        logger.info("创建seesion" + session.getId());
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        try {
            adminSessionMapper.create(new AdminSession(sessionId.toString(), SerializeUtils.serialize(session)));
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("创建SessionToMysql："+e.getMessage());
        }
        return sessionId;

    }

    /**
     * 获取session
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {

        logger.info("读取seesion" + sessionId);

        String sessionStr = adminSessionMapper.get(sessionId.toString());
        if (StringUtils.isBlank(sessionStr)) {
            return null;
        }
        Session session =null;
        try {
            session=  SerializeUtils.deSerialization(sessionStr, session);

        } catch (IOException | ClassNotFoundException e) {
            if(logger.isErrorEnabled()){
                logger.error("读取Session from mysql:"+e.getMessage());
            }
        }
        return session;

    }
}
